package com.tim.app.ui.widget.imagepick.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.application.library.runtime.event.EventManager;
import com.application.library.util.BitmapUtil;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.EventTag;
import com.tim.app.manager.ImagePickerManager;
import com.tim.app.util.ToastUtil;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class ImagePreviewTopicActivity extends ImagePreviewBaseActivity implements View.OnClickListener {

    public static final String IS_DELETE = "isDelete";
    ImageButton btn_back;
    private boolean isDelete;//删除

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ImageView ivDelete = (ImageView) findViewById(R.id.ivDelete);
        isDelete = getIntent().getBooleanExtra(ImagePreviewTopicActivity.IS_DELETE, false);
        if (isDelete) {
            ivDelete.setVisibility(View.VISIBLE);
        } else {
            ivDelete.setVisibility(View.GONE);
        }
        ivDelete.setOnClickListener(this);
        findViewById(R.id.cb_check).setVisibility(View.GONE);

        btn_back = (ImageButton) topBar.findViewById(R.id.btn_back);
        btn_back.setImageResource(R.drawable.ic_back_black);
        mTitleCount.setTextColor(getResources().getColor(R.color.black));

        mTitleCount.setText(getString(R.string.preview_image_count, mCurrentPosition + 1, mImageItems.size()));
        //滑动ViewPager的时候，根据外界的数据改变当前的选中状态和当前的图片的位置描述文本
        mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                mCurrentPosition = position;
                mTitleCount.setText(getString(R.string.preview_image_count, mCurrentPosition + 1, mImageItems.size()));
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_back) {
            onBackPressed();
        } else if (id == R.id.ivDelete) {
            mImageItems.remove(mCurrentPosition);
            mTitleCount.setText(getString(R.string.preview_image_count, mCurrentPosition + 1, mImageItems.size()));
            mAdapter.notifyDataSetChanged();
            EventManager.ins().sendEvent(EventTag.DELETE_ABLUM, 0, 0, mCurrentPosition);
            if (mImageItems.size() == 0) {
                finish();
            }
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    Dexter.checkPermissionOnSameThread(new PermissionListener() {
//                        @Override
//                        public void onPermissionGranted(final PermissionGrantedResponse response) {
//                            saveImage(mImageItems.get(mCurrentPosition).url);
//                        }
//
//                        @Override
//                        public void onPermissionDenied(final PermissionDeniedResponse response) {
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    ToastUtil.showToast(RT.getString(R.string.saveFailed));
//                                }
//                            });
//                        }
//
//                        @Override
//                        public void onPermissionRationaleShouldBeShown(final PermissionRequest permission, final PermissionToken token) {
//                            token.continuePermissionRequest();
//                        }
//                    }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
//                }
//            }).start();

        }
    }

    private void saveImage(String url) {
        Bitmap bitmap = null;
        try {
            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            InputStream is = conn.getInputStream();

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            bitmap = BitmapFactory.decodeStream(is, null, options);
            is.close();
            conn.disconnect();
            String fileName = System.currentTimeMillis() + "";
            final File myCaptureFile = new File(Environment.getExternalStorageDirectory().getPath() + "/download/" + fileName + ".jpg");
            boolean result = BitmapUtil.saveBitmap(bitmap, myCaptureFile);
            if (result) {
                if (result) {
                    // 最后通知图库更新
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myCaptureFile)));
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast(RT.getString(R.string.savaTo, Environment.getExternalStorageDirectory().getPath() + "/download/"));
                        }
                    });
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public int calculateInSampleSize(BitmapFactory.Options options,
                                     int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and
            // keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        //带回最新数据
        intent.putExtra(ImagePickerManager.EXTRA_IMAGE_ITEMS, mImageItems);
        setResult(ImagePickerManager.RESULT_CODE_BACK, intent);
        finish();
        super.onBackPressed();
    }

    /**
     * 单击时，隐藏头和尾
     */
    @Override
    public void onImageSingleTap() {
        if (topBar.getVisibility() == View.VISIBLE) {
            topBar.setAnimation(AnimationUtils.loadAnimation(this, R.anim.top_out));
            topBar.setVisibility(View.GONE);
//            tintManager.setStatusBarTintResource(R.color.transparent);//通知栏所需颜色
            //给最外层布局加上这个属性表示，Activity全屏显示，且状态栏被隐藏覆盖掉。
//            if (Build.VERSION.SDK_INT >= 16)
//                content.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
            hideSystemUI();
        } else {
            topBar.setAnimation(AnimationUtils.loadAnimation(this, R.anim.top_in));
            topBar.setVisibility(View.VISIBLE);
//            tintManager.setStatusBarTintResource(R.color.status_bar);//通知栏所需颜色
            //Activity全屏显示，但状态栏不会被隐藏覆盖，状态栏依然可见，Activity顶端布局部分会被状态遮住
//            if (Build.VERSION.SDK_INT >= 16)
//                content.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            showSystemUI();
        }
    }
}